
package com.tencent.weibo.api
{
	import com.tencent.weibo.lang.MessageCollection;
	import com.tencent.weibo.log.LevelLogger;
	import com.tencent.weibo.operation.IRequestOperation;
	import com.tencent.weibo.operation.URLRequestOperation;
	import com.tencent.weibo.support.WeiboUtil;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	
	import mx.logging.ILogger;

	/**
	 * 基于OAuth授权认证的API。
	 * 当用户第一次使用，您需要使用这个类的方法完成授权，获取到accessToken（后面的API调用都要依赖于accessToken）和密钥。
	 * <h4>示例代码：</h4>
	 * <pre>
	 * var request:IRequestOperation;
	 * var authorizeAPI:Authorize = new Authorize();
	 * request = authorizeAPI.requestToken();
	 * request.addEventListener(Event.COMPLETE,requestTokenHandler);
	 * request.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);
	 * </pre>
	 * 
	 * @langversion 3.0
     * @playerversion Flash 9
     * @playerversion AIR 1.1
	 */	
	public class Authorize extends AbstractAPI
	{
		/**
		 * 日志输出对象
		 */		
		public static var logger:ILogger = LevelLogger.getLogger("com.tencent.weibo.api.Authorize");
		/**
		 * 获取未认证的Token
		 * @return 一个IRequestOperation实例
		 */
		public function requestToken():IRequestOperation
		{
			var url:String = config.encryptURLBase+"request_token";
			var attachParms:Object = {};
			attachParms.oauth_callback = config.oauthCallback;
			var operation:IRequestOperation = consolidationParametersAndSend(url,attachParms);
			operation.addEventListener(Event.COMPLETE,requestTokenHandler);
			return operation;
		}
		/**
		 * 打开用户授权页面
		 * @param pageTarget 窗口模式，默认是_self
		 */			
		public function openUserAuthPage(pageTarget:String="_self"):void
		{
			if(config.tempOauthToken == null)
			{
				logger.error("openUserAuthPage:{0}",MessageCollection.oauthTokenInvalid);
				return;
			}
			var url:String = config.encryptURLBase+"authorize?oauth_token="+config.tempOauthToken;
			navigateToURL(new URLRequest(url),pageTarget);
		}
		/**
		 * 获取access_token
		 * @param oauthVerifier 验证码
		 * @return 一个IRequestOperation实例
		 */		
		public function accessToken(oauthVerifier:String):IRequestOperation
		{
			if(config.tempOauthToken == null)
				logger.error("accessToken:{0}",MessageCollection.oauthTokenInvalid);
			if(oauthVerifier == null || oauthVerifier == "")
				logger.error("accessToken:{0}",MessageCollection.oauthVerifierInvalid);
			var url:String = config.encryptURLBase+"access_token";
			var attachParms:Object = {};
			attachParms.oauth_verifier = oauthVerifier;
			var operation:IRequestOperation = consolidationParametersAndSend(url,attachParms,config.tempOauthToken,config.tempOauthSecret);
			operation.addEventListener(Event.COMPLETE,accessTokenHandler);
			return operation;
		}
		/**
		 * @private
		 */		
		private function requestTokenHandler(event:Event):void
		{
			var validParms:URLVariables = new URLVariables(event.target.data);
			config.tempOauthToken = validParms.oauth_token;
			config.tempOauthSecret = validParms.oauth_token_secret;
			config.cacheToLocal("tempOauthToken",config.tempOauthToken);
			config.cacheToLocal("tempOauthSecret",config.tempOauthSecret);
			//remove listener
			(event.target as EventDispatcher).removeEventListener(Event.COMPLETE,requestTokenHandler);
		}
		/**
		 * @private
		 */		
		private function accessTokenHandler(event:Event):void
		{
			var validParms:URLVariables = new URLVariables(event.target.data);
			config.oauthToken = validParms.oauth_token;
			config.oauthSecret = validParms.oauth_token_secret;
			config.cacheToLocal("oauthToken",config.oauthToken);
			config.cacheToLocal("oauthSecret",config.oauthSecret);
			//clear temp token
			config.tempOauthToken = null;
			config.tempOauthSecret = null;
			config.cacheToLocal("tempOauthToken",null);
			config.cacheToLocal("tempOauthSecret",null);
			//remove listener
			(event.target as EventDispatcher).removeEventListener(Event.COMPLETE,accessTokenHandler);
		}
	}
}